package com.zh.note.leetcode.dp;

/**
 * 718. 最长重复子数组
 */
public class LC_718_findLength {

    public int findLength(int[] nums1, int[] nums2) {
        //dp[i][j] ：以下标i - 1为结尾的A，和以下标j - 1为结尾的B，最长重复子数组长度为dp[i][j]
        int[][] dp = new int[nums1.length + 1][nums2.length + 1];
        int res = 0;
        // 初始化，使用默认初始化为0

        for (int i = 1; i <= nums1.length; i++) {
            for (int j = 1; j <= nums2.length; j++) {
                if (nums1[i - 1] == nums2[j - 1]) {
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                }
                if (dp[i][j] > res) { //结果取dp数组的最大值
                    res = dp[i][j];
                }
            }

        }
        return res;
    }

    public int findLength2(int[] nums1, int[] nums2) {
        //
        int[] dp = new int[nums2.length + 1];
        int res = 0;
        // 初始化，使用默认初始化为0

        for (int i = 1; i <= nums1.length; i++) {
            for (int j = nums2.length; j > 0; j--) {
                if (nums1[i - 1] == nums2[j - 1]) {
                    dp[j] = dp[j - 1] + 1;
                } else {
                    dp[j] = 0;
                }
                if (dp[j] > res) { // 结果取dp数组的最大值
                    res = dp[j];
                }
            }

        }
        return res;
    }

    public int findLength3(int[] nums1, int[] nums2) {
        int len1 = nums1.length;
        int len2 = nums2.length;
        int[][] result = new int[len1][len2];

        int maxresult = Integer.MIN_VALUE;

        for (int i = 0; i < len1; i++) {
            if (nums1[i] == nums2[0])
                result[i][0] = 1;
            if (maxresult < result[i][0])
                maxresult = result[i][0];
        }

        for (int j = 0; j < len2; j++) {
            if (nums1[0] == nums2[j])
                result[0][j] = 1;
            if (maxresult < result[0][j])
                maxresult = result[0][j];
        }

        for (int i = 1; i < len1; i++) {
            for (int j = 1; j < len2; j++) {

                if (nums1[i] == nums2[j])
                    result[i][j] = result[i - 1][j - 1] + 1;

                if (maxresult < result[i][j])
                    maxresult = result[i][j];

            }

        }

        return maxresult;
    }
}
